package com.hp.attendance.serlvet;


import com.hp.attendance.entity.Employee;
import com.hp.attendance.entity.Menu;
import com.hp.attendance.entity.dto.MenuDto;
import com.hp.attendance.service.EmployeeService;
import com.hp.attendance.service.MenuService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private EmployeeService employeeService= new EmployeeService();

    private MenuService menuService = new MenuService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //登录
        try {
            //1.获取登录的用户名和密码
            String employeeNumber = req.getParameter("employeeNumber");
            String password = req.getParameter("password");
            String code1 = req.getParameter("code");
            //2.校验用户名和密码 是否存在  如果存在则登录成功  如果不存在则登录失败
            String code = (String) req.getSession().getAttribute("code");
            // 需要把当前登录用户的菜单查询出来
            Employee employee = employeeService.checkLogin(employeeNumber, password);
            if(employee!=null && employee.getId()!=null){
                //登录成功
                //设置登录标识  把employee对象放入到session
                if (code.equalsIgnoreCase(code1)){
                    req.getSession().setAttribute("emp",employee);
                    // 需要把当前登录用户的菜单查询出来
                    List<MenuDto> listMenus = menuService.getMenuByEmpId(employee.getId());
                    req.setAttribute("listmenus",listMenus);
                    req.getRequestDispatcher("pages/home.jsp").forward(req,resp);
                }else {
                    req.setAttribute("msg","验证码错误");
                    req.getRequestDispatcher("pages/login.jsp").forward(req,resp);
                }

            }else{
                //登录失败
                req.setAttribute("msg","员工编号或密码不正确");
                req.getRequestDispatcher("pages/login.jsp").forward(req,resp);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
